using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Configuration;

public class UrlRedirection : IConfigurationSectionHandler 
{    
    private XmlNode urlrewrites;
    public XmlNode Urlrewrites
    {
        get { return urlrewrites; }
        set { urlrewrites = value; }
    }
    
    private List<RedirectRule> rules;
    public List<RedirectRule> Rules
    {
        get
        {
            if (rules == null)
            {
                rules = GetRules();
            }
            return rules;
        }
    }

    List<RedirectRule> GetRules()
    {
        List<RedirectRule> redirectRules = new List<RedirectRule>();
        UrlRedirection urlRedirection = (UrlRedirection)ConfigurationManager.GetSection("system.web/urlrewrites");
        XmlNode rulesNode = urlRedirection.Urlrewrites;

        foreach (System.Xml.XmlNode ruleNode in rulesNode.SelectNodes("rule"))
        {
            if ((ruleNode.SelectSingleNode("url/text()") != null) &&
                (ruleNode.SelectSingleNode("rewrite/text()") != null))
            {
                RedirectRule redirectRule = new RedirectRule();
                redirectRule.Name = ruleNode.Attributes["name"].Value;
                redirectRule.URL = ruleNode.SelectSingleNode("url/text()").Value;
                redirectRule.RewriteURL = ruleNode.SelectSingleNode("rewrite/text()").Value;
                redirectRules.Add(redirectRule);
            }
        }
        return redirectRules;
    }

    public string GetMatchingRewrite(string URL)
    {
        string returnUrl = "";
        Regex regex;
        foreach (RedirectRule redirectRule in Rules)
        {
            regex = new Regex(redirectRule.URL);
            Match oMatch = regex.Match(URL);
            if (oMatch.Success)
            {
                returnUrl = regex.Replace(URL, redirectRule.RewriteURL);
            }
        }
        return returnUrl;
    }

    #region Implementation of IConfigurationSectionHandler
    public object Create(object parent, object configContext, XmlNode section)
    {
        urlrewrites = section;
        return this;
    }
    #endregion
}